package com.feihong.txgw.utils.facetools;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;

import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.utils.CatchFileUtils;
import com.feihong.txgw.utils.RetrofitUtil;
import com.feihong.txgw.utils.TImageUtils;
import com.feihong.txgw.utils.manage.RetrofitManager;

import org.json.JSONObject;

import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by Sabirjan on 2017/7/5.
 * TXGWApp.
 * 飞宏电子
 * 人脸图片上传并 face验证
 */

public class UploadAndVerifyFace extends Thread {

    private static final String TAG = "通讯顾问";
    private static final String VERIFY_URL = "https://api.megvii.com/faceid/v2/verify";
    private static final String UPLOAD_IMAGE_URL = HttpTools.HTTP_HOME + "App/Api/upload";

    private UploadCallBack callBack;
    private Context mContext;
    /**
     * 上传的最好的人脸图片  【活体检测返回】
     */
    private Bitmap bitmap = null;
    /**
     * 身份证的Base64图片
     */
    private String cardImage = "";
    /**
     * 活体检测返回的信息 【活体检测返回】
     */
    private String delta = "";
    /**
     * 【活体检测返回】
     */
    private Map<String, byte[]> images = new HashMap<>();
    /**
     * 活体检测本地保存的照片
     */
    private File personFile;
    /**
     * 上传的图片地址
     */
    private String uploadFileUrl = "";
    /**
     * 身份证号码
     */
    private String cardID = "";

    private String faceMessage = "";

    public UploadAndVerifyFace(Context context, UploadCallBack callBack) {
        this.mContext = context;
        this.callBack = callBack;

    }

    /**
     * 初始化 数据
     *
     * @param facebitmap 人脸图片  【活体检测返回】
     * @param cardImage  身份证的Base64图片
     * @param cardID     身份证号码
     * @param delta      活体检测返回的信息 【活体检测返回】
     * @param images     活体检测返回图片【活体检测返回】
     */
    public void initData(Bitmap facebitmap, String cardImage, String cardID, String delta, Map<String, byte[]> images) {
        this.bitmap = facebitmap;
        this.cardImage = cardImage;
        this.delta = delta;
        this.images = images;
        this.cardID = cardID;
    }

    public void setFaceBitmap(Bitmap facebitmap) {
        this.bitmap = facebitmap;
    }

    public void setCardID(String cardID) {
        this.cardID = cardID;
    }

    public void setCardImage(String cardImage) {
        this.cardImage = cardImage;
    }

    public void setDelta(String delta) {
        this.delta = delta;
    }

    public void setImages(Map<String, byte[]> images) {
        this.images = images;
    }

    /**
     * 开始上传
     */
    public void startUpload() {
        Message message = new Message();
        if (this.bitmap == null) {
            message.what = -1;
            message.obj = "上传的文件对象不能为空！";
            mHanlder.sendMessage(message);
            return;
        }
        if (this.cardImage == null || this.cardImage.trim().length() == 0) {
            message.what = -1;
            message.obj = "身份证图片不能为空！";
            mHanlder.sendMessage(message);
            return;
        }
        if (this.delta == null || this.delta.trim().length() == 0) {
            message.what = -1;
            message.obj = "活体检测校验码不能为空！";
            mHanlder.sendMessage(message);
            return;
        }
        if (this.cardID == null || this.cardID.trim().length() < 15) {
            message.what = -1;
            message.obj = "身份证号码有误";
            mHanlder.sendMessage(message);
            return;
        }
        if (this.images == null || this.images.size() == 0) {
            message.what = -1;
            message.obj = "活体检测图片集合不能为空！";
            mHanlder.sendMessage(message);
            return;
        }
        this.start();
    }

    Handler mHanlder = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what > 0) {

                if (msg.what == 100) {
                    if (callBack != null) {
                        callBack.success(uploadFileUrl, 1, faceMessage);
                    }
                } else {
                    if (callBack != null) {
                        callBack.success(uploadFileUrl, -1, faceMessage);
                    }
                }


            } else {
                if (callBack != null) {
                    callBack.error(msg.obj.toString());
                }
            }
        }
    };


    @Override
    public void run() {
        Message message = new Message();
        try {
            File afile = TImageUtils.saveBitmapFile(bitmap);
            RequestBody imageBody = RetrofitUtil.toRequestBodyOfImage(afile);
            MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", afile.getName(), imageBody);
//            MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", "severImg", imageBody);
            String uploadResult = null;
            try {
                uploadResult = RetrofitManager.getInstance().upLoadImgToServer(imageBodyPart).execute().body();
                if (uploadResult == null || uploadResult.trim().length() == 0) {
                    throw new Throwable("上传图片返回的内容为空");
                }
            } catch (Throwable throwable) {
                message.what = -1;
                message.obj = "上传图片失败";
                mHanlder.sendMessage(message);
                return;
            }
            JSONObject jsonObject = new JSONObject(uploadResult);
            int status = jsonObject.getInt("status");
            uploadFileUrl = jsonObject.getString("filename");
            if (status != 1 || uploadFileUrl == null || uploadFileUrl.trim().length() == 0) {
                message.what = -1;
                message.obj = "上传图片失败\n" + jsonObject.getString("message");
                mHanlder.sendMessage(message);
                return;
            }
            byte[] bytes;
            bytes = Base64.decode(cardImage, Base64.NO_WRAP);

            //   ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(bytes);
            //  requestParams.addParameter("image_ref1", byteArrayInputStream2);// 传入身份证头像照片路径
            try {
                OutputStream outputStream = mContext.openFileOutput(CatchFileUtils.Person_IMAGE_NAME, Context.MODE_PRIVATE);
                outputStream.write(bytes);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(mContext.getFilesDir(), CatchFileUtils.Person_IMAGE_NAME);
            // 传入身份证头像照片路径
            RequestBody ref1ImgBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part ref1ImgPart = MultipartBody.Part.createFormData("image_ref1", file.getName(), ref1ImgBody);
            int fileIndex = 1;
            Map<String, RequestBody> mImgParams = new HashMap<>();
            for (Map.Entry<String, byte[]> entry : images.entrySet()) {
                try {
                    OutputStream outputStream = mContext.openFileOutput("image" + fileIndex + ".png", Context.MODE_PRIVATE);
                    outputStream.write(entry.getValue());
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                File tempfile = new File(mContext.getFilesDir(), "image" + fileIndex + ".png");
                mImgParams.put(entry.getKey()+"\"; filename=\"" + entry.getKey(), RetrofitUtil.toRequestBodyOfImage(tempfile));
                fileIndex++;
            }
            mImgParams.put("image_ref1\"; filename=\"" + file.getName(), ref1ImgBody);
            mImgParams.put("uuid",RetrofitUtil.toRequestBodyOfText(cardID));
            mImgParams.put("delta",RetrofitUtil.toRequestBodyOfText(delta));
            mImgParams.put("api_key",RetrofitUtil.toRequestBodyOfText("iOzZNlHB2fsz_Bj_3_C2GN5vOdLIoNBc"));
            mImgParams.put("api_secret",RetrofitUtil.toRequestBodyOfText("G3Dliy_up17PCxP6Z_sc3VTlNQSl7v_X"));
            mImgParams.put("comparison_type",RetrofitUtil.toRequestBodyOfText("0"));
            mImgParams.put("face_image_type",RetrofitUtil.toRequestBodyOfText("meglive"));
            mImgParams.put("uuid",RetrofitUtil.toRequestBodyOfText(cardID));
            String verify_result = "";
            try {
                verify_result = RetrofitManager.getInstance().upLoadImgToMegvii(HttpTools.VERIFY_URL,mImgParams).execute().body();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            if (verify_result == null || verify_result.contains("error_message")) {
                throw new Exception("验证失败！");
            }
            JSONObject object = new JSONObject(verify_result);
            JSONObject jObject = object
                    .getJSONObject("result_ref1");
            double idcard_confidence = jObject
                    .getDouble("confidence");
            double idcard_tenThreshold = jObject
                    .getJSONObject("thresholds")
                    .getDouble("1e-4");
            // 解析faceGen
            JSONObject jObject1 = object
                    .getJSONObject("face_genuineness");

            float mask_confidence = (float) jObject1
                    .getDouble("mask_confidence");
            float mask_threshold = (float) jObject1
                    .getDouble("mask_threshold");
            float screen_replay_confidence = (float) jObject1
                    .getDouble("screen_replay_confidence");
            float screen_replay_threshold = (float) jObject1
                    .getDouble("screen_replay_threshold");

            float synthetic_face_confidence = (float) jObject1
                    .getDouble("synthetic_face_confidence");
            float synthetic_face_threshold = (float) jObject1
                    .getDouble("synthetic_face_threshold");
            int face_replaced = jObject1.getInt("face_replaced");

            if (mask_confidence >= 0.2) {
                //"面具攻击，识别不通过！"
                faceMessage = "面具攻击，识别不通过！";
            } else if (screen_replay_confidence >= 0.2) {
                // "屏幕翻拍，识别不通过！"
                faceMessage = "屏幕翻拍，识别不通过！";
            } else if (synthetic_face_confidence >= 0.2) {
                //"软件合成，识别不通过！"
                faceMessage = "软件合成，识别不通过！";
            } else if (face_replaced == 1) {
                // 0表示未检测出换脸攻击，1表示检测出了换脸攻击
                //检测出了换脸攻击
                faceMessage = "检测出了换脸攻击";
            } else {
                if (idcard_confidence >= idcard_tenThreshold) {
                    //
                    faceMessage = "成功";
                    mHanlder.sendEmptyMessage(100);
                    return;
                } else {
                    //"识别未通过，请重新验证！"
                    faceMessage = "识别未通过，请重新验证！";
                }
            }
            mHanlder.sendEmptyMessage(88);


        } catch (Exception ex) {
            ex.printStackTrace();

            if (uploadFileUrl != null && uploadFileUrl.trim().length() > 0) {
                faceMessage = ex.getMessage();
                //上传成功了，但是验证失败
                mHanlder.sendEmptyMessage(99);
            } else {
                message.what = -1;
                message.obj = "程序出错！验证失败 \n" + ex.getMessage();
                mHanlder.sendMessage(message);
                return;
            }

        }
    }
}
